<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div class="p-2" style="display: flex">
    <div class="structure_left" :style="{ width: leftWidth - 0.3 + '%' }">
      <el-card class="card" shadow="never" @scroll="handleScroll">
        <el-input
          v-model="queryName"
          placeholder="请输入节点或模型名称"
          prefix-icon="Search"
          clearable
          style="margin-bottom: 10px"
          @clear="clearQuery"
        />
        <div style="display: flex; align-items: center; margin-bottom: 6px; flex-wrap: wrap">
          <span class="explanation">符号说明：</span>
          <span class="sub_explanation"> <img :src="database" alt="" style="height: 20px; width: 16px; margin-right: 5px" />要素数据库</span>
          <span class="sub_explanation"><img :src="Scene" alt="" style="height: 20px; width: 18px; margin-right: 5px" />业务场景</span>
          <span class="sub_explanation"> <img :src="system" alt="" style="height: 20px; width: 18px; margin-right: 5px" />业务系统</span>
          <span class="sub_explanation"> <img :src="model" alt="" style="height: 20px; width: 16px; margin-right: 5px" />普通模型</span>
          <span class="sub_explanation"> <img :src="generalModel" alt="" style="height: 20px; width: 16px; margin-right: 5px" />通用模型</span>
        </div>
        <el-tree
          ref="deptTreeRef"
          class="tree"
          :indent="0"
          default-expand-all
          highlight-current
          :data="treeData"
          node-key="id"
          :props="defaultProps"
          :filter-node-method="filterNode"
          :expand-on-click-node="false"
          @node-contextmenu="openMenu"
          @node-click="handleNodeClick"
        >
          <template #default="{ data }">
            <el-tooltip :disabled="tooltipVisible" effect="dark" :content="data.name" placement="top">
              <span style="display: flex; align-items: center" @mouseover="handleNodeMouseOver">
                <img :src="getImageSrc(data)" alt="" style="height: 16px; width: 16px" />
                <span class="sub_title">{{ data.name }}</span>
              </span>
            </el-tooltip>
          </template>
        </el-tree>
        <div v-show="menuVisible" ref="wrapper" :style="menuStyle" class="custom-menu">
          <ul>
            <li v-if="nodeType === 'root'" @click="handleMenuClick('database')">
              <el-button size="small" link type="primary" icon="Plus">添加要素库</el-button>
            </li>
            <li v-if="nodeType === 'database_1'" @click="handleMenuClick('database_1')">
              <el-button size="small" link type="primary" icon="Plus">添加要素库</el-button>
            </li>
            <li v-if="nodeType === 'database_1' || nodeType === 'database_2'" @click="handleMenuClick('scene')">
              <el-button size="small" link type="primary" icon="Plus">添加业务场景</el-button>
            </li>
            <li v-if="nodeType === 'scene'" @click="handleMenuClick('system')">
              <el-button size="small" link type="primary" icon="Plus">添加业务系统</el-button>
            </li>
            <li v-if="nodeType === 'scene' || nodeType === 'common_model'" @click="handleMenuClick('addModel')">
              <el-button size="small" link type="primary" icon="Plus">添加通用模型</el-button>
            </li>
            <li v-if="nodeType === 'system' || nodeType === 'model'" @click="handleMenuClick('addModel')">
              <el-button size="small" link type="primary" icon="Plus">添加普通模型</el-button>
            </li>
            <li v-if="menuLevel !== 1" @click="handleMenuClick('delete')">
              <el-button size="small" link type="primary" icon="Delete">删除</el-button>
            </li>
          </ul>
        </div>
      </el-card>
    </div>
    <div class="resizer" @mousedown.prevent="startResize"></div>
    <div class="model_display" :style="{ width: 100 - leftWidth + '%' }" style="height: calc(100vh - 100px); overflow: auto">
      <el-card shadow="never" style="margin-bottom: 10px">
        <el-form :inline="true" size="small" label-width="100px">
          <el-form-item label="模型名称：" prop="data">
            <el-input v-model="queryParams.modelName" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item label="模型类型：" prop="data">
            <el-select v-model="queryParams.modelType" placeholder="请选择" clearable>
              <el-option label="普通模型" value="model"></el-option>
              <el-option label="通用模型" value="common_model"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="search" @click="doQuery">查询</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <el-card shadow="never" style="overflow: auto">
        <template #header>
          <el-button type="primary" size="small" icon="plus" style="margin-bottom: 5px" @click="buttonClick('add', null)">添加模型</el-button>
        </template>

        <el-table v-loading="loading" :data="metaList" style="width: 100%" row-key="id" border>
          <el-table-column label="模型名称" align="left" prop="modelName" fixed="left" show-overflow-tooltip />
          <el-table-column label="模型标识" align="left" prop="id" show-overflow-tooltip />
          <el-table-column label="模型类型" align="left" prop="modelType" show-overflow-tooltip>
            <template #default="scope">
              {{ scope.row.modelType === 'model' ? '普通模型' : '通用模型' }}
            </template>
          </el-table-column>
          <el-table-column label="所属节点" align="left" prop="nodeName" show-overflow-tooltip />
          <el-table-column label="父级模型" align="left" prop="parentConfigName" show-overflow-tooltip
            ><template #default="scope">
              {{ scope.row.parentConfigName || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="父级模型元素" align="left" prop="parentConfigFieldName" show-overflow-tooltip>
            <template #default="scope">
              {{ scope.row.parentConfigFieldName || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="版本号" align="left" prop="versionNumber" show-overflow-tooltip>
            <template #default="scope">
              {{ scope.row.parentConfigName ? '-' : scope.row.versionNumber }}
            </template>
          </el-table-column>
          <el-table-column label="模型描述" align="left" prop="description" show-overflow-tooltip>
            <template #default="scope">
              {{ scope.row.description || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="left" width="200" fixed="right">
            <template #default="scope">
              <el-button size="small" link type="primary" icon="Document" @click="buttonClick('view', scope.row)">详情</el-button>
              <el-button
                v-if="scope.row.canUpgrade === 0 && scope.row.isPublished === 0 && scope.row.isLastestVersion === 1"
                size="small"
                link
                type="primary"
                icon="EditPen"
                @click="buttonClick('edit', scope.row)"
                >编辑</el-button
              >
              <el-button
                v-if="
                  scope.row.canUpgrade === 0 && scope.row.parentConfigId == null && scope.row.isLastestVersion === 1 && scope.row.isPublished === 1
                "
                size="small"
                link
                type="primary"
                icon="EditPen"
                @click="buttonClick('upgrade', scope.row)"
                >升版</el-button
              >
              <el-button
                v-if="scope.row.isPublished === 0 && scope.row.isLastestVersion === 1"
                size="small"
                link
                type="primary"
                icon="Delete"
                @click="buttonClick('delete', scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <template #footer>
          <pagination
            v-show="total > 0"
            style="margin-top: 0"
            v-model:page="queryParams.pageQuery.pageNum"
            v-model:limit="queryParams.pageQuery.pageSize"
            :total="total"
            :background="false"
            layout="total, sizes, prev, pager, next, jumper"
            @pagination="getList"
          />
        </template>
      </el-card>
    </div>
  </div>

  <el-dialog v-model="dialogVisible" :title="dialogTitle" style="width: 500px" @close="resetDialog">
    <el-form ref="nodeRef" :rules="nodeFormRules" :model="nodeFormCopy" label-width="120px">
      <el-form-item :label="dialogLabel" prop="businessId">
        <el-select
          v-if="dialogLabel !== '选择要素库：'"
          v-model="nodeFormCopy.businessId"
          placeholder="请选择"
          clearable
          @change="handleSelectChange"
        >
          <el-option v-for="item in selectList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
        </el-select>
        <el-cascader
          v-else
          v-model="path"
          ref="cascader"
          style="width: 100%"
          :options="databaseListCopy"
          placeholder="请选择要素数据库"
          :props="cascaderProps"
          @change="handleCascaderChange"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="resetDialog">取消</el-button>
        <el-button type="primary" @click="submitForm('noModel')">确认</el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog v-model="upgradeVisible" :title="'模型升版'" style="width: 500px" @close="resetDialog">
    <el-form :model="upgradeForm" label-width="100px">
      <el-form-item label="新版本号:" prop="versionNumber">
        <el-input v-model="upgradeForm.versionNumber" placeholder="请输入新版本号" clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="resetDialog">取消</el-button>
        <el-button type="primary" @click="submitForm('version')">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import system from '@/assets/images/modelEstablish/system.svg';
import database from '@/assets/images/modelEstablish/database.svg';
import model from '@/assets/images/modelEstablish/model.svg';
import home from '@/assets/images/modelEstablish/home.svg';
import Scene from '@/assets/images/modelEstablish/Scene.svg';
import generalModel from '@/assets/images/modelEstablish/generalModel.svg';
import { getTreeList } from '@/api/databaseManagement';
import { getBusinessSystemList } from '@/api/businessSystem';
import { getElementModel, getModellTree, addModelTreeNode, deleteModelTreeNode, deleteElementModel, upgradeModel } from '@/api/metaData/model.ts';
const props = defineProps(['modelId', 'nodeId', 'cardScrollTop']);
const emits = defineEmits(['handleEvent']);
const businessSystemList = ref([]);
const businessScenariosList = ref([]);
const databaseList = ref([]);
const databaseListCopy = ref([]);
const dialogLabel = ref('');
const selectList = ref([]);
const cascader = ref();
const cascaderProps = ref({
  value: 'id',
  label: 'databaseName',
  children: 'children',
  checkStrictly: true,
  disabled: (data: any) => {
    return isIdInTreeData(data.id);
  }
});
const path = ref([]);
const nodeForm = ref({
  type: '',
  parentId: '',
  name: '',
  businessId: ''
});
const nodeFormCopy = ref(JSON.parse(JSON.stringify(nodeForm.value)));
const nodeRef = ref();
const leftWidth = ref(20);
const deptTreeRef = ref<ElTreeInstance>();
const queryName = ref('');
const defaultProps = { children: 'children', label: 'label' };
const wrapper = ref(null);
const treeData = ref([]);
const menuVisible = ref(false);
const menuStyle = ref({ left: 0, top: 0 });
const menuLevel = ref(null);
const nodeType = ref('');
const nodeContent = ref(null);
const dialogVisible = ref(false);

const metaList = ref([]);
const loading = ref(false);
const total = ref(0);
const queryParams = ref({
  nodeId: props.nodeId ? props.nodeId : '1879453303423115265',
  modelId: props.modelId ? props.modelId : '',
  pageQuery: {
    pageNum: 1,
    pageSize: 10,
    orderByColumn: 'id',
    isAsc: 'descending'
  },
  modelName: '',
  modelType: ''
});
const dialogTitle = ref('');
const parentId = ref(null);
const upgradeVisible = ref(false);
const initialModelId = ref('');
const upgradeForm = ref({
  previousVersionId: '',
  versionNumber: ''
});
const treeScrollTop = ref(0);
const currentTop = ref(0);
const isChange = ref(false);
const isDelete = ref(false);
const nodeFormRules = {
  businessId: [{ required: true, message: '请输入节点名称', trigger: 'blur' }]
};
const handleScroll = (event) => {
  treeScrollTop.value = event.target.scrollTop;
  currentTop.value = event.target.scrollTop;
  isChange.value = true;
};
const resetDialog = () => {
  dialogVisible.value = false;
  path.value = [];
  databaseListCopy.value = JSON.parse(JSON.stringify(databaseList.value));
  nodeFormCopy.value = JSON.parse(JSON.stringify(nodeForm.value));
  upgradeVisible.value = false;
  upgradeForm.value = {
    previousVersionId: '',
    versionNumber: ''
  };
};

const tooltipVisible = ref(true);
// 新增 handleNodeMouseOver 函数用于处理鼠标悬停事件
const handleNodeMouseOver = (node) => {
  var target = node.target;
  let textLength = target.clientWidth;
  const nodeContent = target.closest('.el-tree-node__content');
  const containerWidth = nodeContent.clientWidth; // 获取包含 padding+border 的完整宽度
  console.log(textLength, containerWidth);
  if (textLength + 55 < containerWidth) {
    tooltipVisible.value = true;
  } else {
    tooltipVisible.value = false;
  }
};

// 过滤树结构
const filterNode = (value, data) => {
  if (!value) return true;
  return data.name.indexOf(value) !== -1;
};
const clearQuery = () => {
  deptTreeRef.value?.setCurrentKey('1879453303423115265');
  queryParams.value = {
    nodeId: '1879453303423115265',
    modelId: '',
    pageQuery: {
      pageNum: 1,
      pageSize: 10,
      orderByColumn: 'id',
      isAsc: 'descending'
    },
    modelName: '',
    modelType: ''
  };
  getList();
};

// 初始化图标
const getImageSrc = (data) => {
  if (data.type === 'root') {
    return home;
  } else if (data.type === 'database_1' || data.type === 'database_2') {
    return database;
  } else if (data.type === 'scene') {
    return Scene;
  } else if (data.type === 'system') {
    return system;
  } else if (data.type === 'model') {
    return model;
  } else if (data.type === 'common_model') {
    return generalModel;
  }
  return null;
};

watchEffect(
  () => {
    deptTreeRef.value?.filter(queryName.value);
  },
  {
    flush: 'post'
  }
);

// 获取最近节点信息
const nodeData = (data, node) => {
  // 终止条件：没有父节点或父节点数据为空
  if (!node.parent || !node.parent.data) return null;
  if (data.type !== 'node') {
    return nodeData(node.parent.data, node.parent);
  } else {
    return data;
  }
};

// 右键菜单
const openMenu = (event, data, node) => {
  // 安全访问 parent.data.id
  parentId.value = node.parent?.data?.id || '';
  // 处理可能返回的 null
  // nodeParent.value = nodeData(data, node) || { id: '' };
  menuLevel.value = node.level;
  nodeType.value = node.data.type;
  nodeContent.value = data;
  menuVisible.value = true;
  event.preventDefault();
  menuStyle.value.left = 220 + 'px';
  menuStyle.value.top = event.clientY - 110 + 'px';
};

// 数据处理
const handleSelectChange = (value) => {
  nodeFormCopy.value.name = selectList.value.find((item) => item.id === value)?.name;
};
// 绑定数据库
const handleCascaderChange = (valueArr) => {
  console.log(valueArr);
  cascader.value.togglePopperVisible(false);
  nodeFormCopy.value.businessId = valueArr[valueArr.length - 1];
  if (nodeFormCopy.value.type === 'database') {
    nodeFormCopy.value.type = 'database_2';
  } else {
    if (valueArr.length === 1) {
      nodeFormCopy.value.type = 'database_1';
    } else if (valueArr.length === 2) {
      nodeFormCopy.value.type = 'database_2';
    }
  }
  const selectedNode = findNodeByIds(databaseListCopy.value, valueArr);
  nodeFormCopy.value.name = selectedNode.databaseName;
};

// 获取级联选择器节点数据
const findNodeByIds = (nodes, ids) => {
  for (const node of nodes) {
    if (node.id === ids[ids.length - 1]) {
      return node;
    }
    if (node.children) {
      const foundNode = findNodeByIds(node.children, ids);
      if (foundNode) {
        return foundNode;
      }
    }
  }
  return null;
};

// 递归处理不可选要素库
const isIdInTreeData = (id) => {
  const searchNode = (nodes) => {
    for (const node of nodes) {
      if (node.businessId === id) return true;
      if (node.children && searchNode(node.children)) return true;
    }
    return false;
  };
  return searchNode(treeData.value);
};

// 获取树结构要素库数据
const findDatabaseListNodeByIds = (nodes, ids) => {
  for (const node of nodes) {
    if (node.businessId === ids[ids.length - 1]) {
      return node;
    }
    if (node.children) {
      const foundNode = findDatabaseListNodeByIds(node.children, ids);
      if (foundNode) {
        return foundNode;
      }
    }
  }
  return null;
};

// 树结构操作
const handleMenuClick = (type) => {
  if (type === 'database') {
    dialogTitle.value = '添加要素库';
    dialogVisible.value = true;
    nodeFormCopy.value.businessId = '';
    nodeFormCopy.value.name = '';
    nodeFormCopy.value.parentId = nodeContent.value.id;
    dialogLabel.value = '选择要素库：';
    selectList.value = databaseListCopy.value;
  }
  if (type === 'database_1') {
    dialogTitle.value = '添加要素库';
    dialogVisible.value = true;
    nodeFormCopy.value.businessId = '';
    nodeFormCopy.value.type = 'database';
    nodeFormCopy.value.name = '';
    nodeFormCopy.value.parentId = nodeContent.value.id;
    dialogLabel.value = '选择要素库：';
    selectList.value = databaseListCopy.value;
    const selectedNode = findNodeByIds(databaseListCopy.value, [nodeContent.value.businessId]);
    databaseListCopy.value = [selectedNode];
  }
  if (type === 'scene') {
    dialogTitle.value = '添加业务场景';
    dialogVisible.value = true;
    nodeFormCopy.value.businessId = '';
    nodeFormCopy.value.type = 'scene';
    nodeFormCopy.value.name = '';
    nodeFormCopy.value.parentId = nodeContent.value.id;
    dialogLabel.value = '选择业务场景：';
    selectList.value = businessScenariosList.value;
  }
  if (type === 'system') {
    dialogTitle.value = '添加业务系统';
    dialogVisible.value = true;
    nodeFormCopy.value.businessId = '';
    nodeFormCopy.value.type = 'system';
    nodeFormCopy.value.name = '';
    nodeFormCopy.value.parentId = nodeContent.value.id;
    dialogLabel.value = '选择业系统：';
    getBusinessSystemList({
      parentId: nodeContent.value.businessId,
      type: 1,
      pageNum: 1,
      pageSize: 9999
    }).then((res) => {
      if (res) {
        businessSystemList.value = res.rows || [];
        selectList.value = businessSystemList.value;
      }
    });
  }
  if (type === 'addModel') {
    menuVisible.value = false;
    console.log('nodeContent.value', nodeContent.value);
    if (!nodeContent.value.hasOwnProperty('hasEligibleField') || nodeContent.value.hasEligibleField === true) {
      const params = {
        modelParentType:
          nodeType.value === 'model' || nodeType.value === 'common_model'
            ? nodeContent.value.type
            : nodeType.value === 'scene'
              ? 'common_model'
              : 'model',
        nodeId: nodeType.value === 'model' || nodeType.value === 'common_model' ? nodeContent.value.nodeId : nodeContent.value.id,
        nodeName: nodeType.value === 'model' ? '' : nodeContent.value.name,
        parentModelId: nodeType.value === 'model' || nodeType.value === 'common_model' ? nodeContent.value.id : '',
        parentConfigName: nodeType.value === 'model' || nodeType.value === 'common_model' ? nodeContent.value.name : '',
        treePath: nodeType.value === 'model' || nodeType.value === 'common_model' ? '' : nodeContent.value.uniqueKey,
        isEditble: true,
        systemId: '',
        systemName: '',
        sceneId: '',
        sceneName: '',
        databaseTypeId: '',
        databaseTypeName: ''
      };
      console.log('treePath', params.treePath);
      if (params.treePath) {
        params.treePath = params.treePath.split('_');
        // 业务场景/业务系统
        if (nodeType.value === 'system') {
          params.systemId = params.treePath.pop();
          params.sceneId = params.treePath.pop();
          params.databaseTypeId = params.treePath.pop();
        } else if (nodeType.value === 'scene') {
          params.sceneId = params.treePath.pop();
          params.databaseTypeId = params.treePath.pop();
        }
      }
      const databaseNode = findDatabaseListNodeByIds(treeData.value, [params.databaseTypeId]);
      if (databaseNode) {
        params.databaseTypeName = databaseNode.name;
        const sceneNode = findDatabaseListNodeByIds([databaseNode], [params.sceneId]);
        console.log('sceneNode', sceneNode);
        if (sceneNode) {
          params.sceneName = sceneNode.name;
          const systemNode = findDatabaseListNodeByIds([sceneNode], [params.systemId]);
          if (systemNode) {
            params.systemName = systemNode.name;
          }
        }
      }
      emits('handleEvent', {
        component: 'add',
        row: params,
        nodeId: queryParams.value.nodeId,
        modelId: queryParams.value.modelId,
        cardScrollTop: treeScrollTop.value
      });
    } else {
      ElMessageBox.alert('该模型没有可关联的字段，请选择其他模型或在该模型中添加 "模型" 类型的字段', '提示', {
        confirmButtonText: '确定',
        type: 'warning'
      });
    }
  }
  if (type === 'delete') {
    menuVisible.value = false;
    ElMessageBox.confirm('确认要删除该数据项吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      if (nodeContent.value.type === 'model' || nodeContent.value.type === 'common_model') {
        deleteElementModel(nodeContent.value.id).then((res) => {
          if ((res.code = 200)) {
            ElMessage({ showClose: true, message: '删除成功。', type: 'success' });
            if (metaList.value.length === 1) {
              isDelete.value = true;
              getList();
            } else {
              getList();
            }
            getTreeData();
          }
        });
      } else {
        deleteModelTreeNode(nodeContent.value.id).then((res) => {
          if ((res.code = 200)) {
            ElMessage({ showClose: true, message: '删除成功。', type: 'success' });
            getTreeData();
          }
        });
      }
    });
  }
};

// 保存节点信息
const submitForm = (type) => {
  if (type === 'noModel') {
    nodeRef.value.validate((valid) => {
      if (!valid) {
        return;
      } else {
        console.log(' nodeFormCopy.value', nodeFormCopy.value);
        addModelTreeNode(nodeFormCopy.value).then((res) => {
          if (res.code === 200) {
            ElMessage({ showClose: true, message: '保存成功', type: 'success' });
            nodeFormCopy.value = ref(JSON.parse(JSON.stringify(nodeForm.value)));
            databaseListCopy.value = JSON.parse(JSON.stringify(databaseList.value));
            dialogVisible.value = false;
            getTreeData();
          }
        });
      }
    });
  }
  if (type === 'version') {
    upgradeModel(upgradeForm.value)
      .then((res) => {
        if (res) {
          ElMessage({ showClose: true, message: '保存成功', type: 'success' });
          upgradeVisible.value = false;
          getList();
          getTreeData();
        }
      })
      .catch(() => {
        ElMessage({ showClose: true, message: '保存失败', type: 'error' });
      });
  }
};

// 失去焦点隐藏菜单
const handleClick = (event) => {
  if (wrapper.value && !wrapper.value.contains(event.target)) {
    menuVisible.value = false;
  }
};

// 左键点击节点获取模型列表
const handleNodeClick = (data, node) => {
  menuVisible.value = false;
  // nodeParent.value = nodeData(data, node);
  if (data.type !== 'model' && data.type !== 'common_model') {
    queryParams.value.modelId = '';
    queryParams.value.nodeId = data.id;
  } else {
    initialModelId.value = Object.values(data.versionIdMap).at(-1);
    // queryParams.value.nodeId = nodeParent.value.id;
    queryParams.value.nodeId = data.nodeId;
    queryParams.value.modelId = initialModelId.value;
  }
  getList();
};

const doQuery = () => {
  getList();
};

const resetQuery = () => {
  queryParams.value = {
    nodeId: queryParams.value.nodeId || '1879453303423115265',
    modelId: queryParams.value.modelId || '',
    pageQuery: {
      pageNum: 1,
      pageSize: 10,
      orderByColumn: 'id',
      isAsc: 'descending'
    },
    modelName: '',
    modelType: ''
  };
  getList();
};

const buttonClick = (type, data) => {
  if (type === 'add') {
    emits('handleEvent', {
      component: 'add',
      row: data,
      nodeId: queryParams.value.nodeId,
      modelId: queryParams.value.modelId,
      cardScrollTop: treeScrollTop.value
    });
  }
  if (type === 'edit') {
    emits('handleEvent', {
      component: 'modify',
      row: { ...data, isEditble: true },
      nodeId: queryParams.value.nodeId,
      modelId: queryParams.value.modelId,
      cardScrollTop: treeScrollTop.value
    });
  }
  if (type === 'delete') {
    ElMessageBox.confirm('确认要删除该数据项吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      deleteElementModel(data.id)
        .then((res) => {
          if (res) {
            ElMessage({ showClose: true, message: '删除成功。', type: 'success' });
            if (metaList.value.length === 1) {
              isDelete.value = true;
              getList();
            } else {
              getList();
            }
            getTreeData();
          }
        })
        .catch(() => {
          ElMessage({ showClose: true, message: '删除失败。', type: 'error' });
        });
    });
  }
  if (type === 'view') {
    emits('handleEvent', {
      component: 'view',
      row: data,
      nodeId: queryParams.value.nodeId,
      modelId: queryParams.value.modelId,
      cardScrollTop: treeScrollTop.value
    });
  }
  if (type === 'upgrade') {
    upgradeVisible.value = true;
    upgradeForm.value.previousVersionId = data.id;
  }
};

const getTreeData = () => {
  const params = {
    id: null
  };
  getModellTree(params)
    .then((res) => {
      if (res) {
        treeData.value = [res.data];
        // 初始化滚轮位置以及高亮
        nextTick(() => {
          let x = document.getElementsByClassName('card')[0];
          if (isChange.value === true) {
            isChange.value = false;
            x.scrollTop = currentTop.value; //复原滚轮位置
          } else {
            x.scrollTop = props.cardScrollTop; //复原滚轮位置
          }
          if (isDelete.value === true) {
            isDelete.value = false;
            deptTreeRef.value?.setCurrentKey('1879453303423115265');
            x.scrollTop = 0;
          } else if (props.nodeId && props.modelId) {
            // 反回到模型
            deptTreeRef.value?.setCurrentKey(metaList.value[0].id);
          } else if (props.nodeId && !props.modelId) {
            // 返回到节点
            deptTreeRef.value?.setCurrentKey(props.nodeId);
          } else if (queryParams.value.nodeId && queryParams.value.modelId) {
            // 定位到模型
            deptTreeRef.value?.setCurrentKey(metaList.value[0].id);
          } else if (queryParams.value.nodeId && !queryParams.value.modelId) {
            // 定位到节点
            deptTreeRef.value?.setCurrentKey(queryParams.value.nodeId);
          }
        });
      }
    })
    .catch(() => {
      treeData.value = [];
    })
    .finally(() => {
      loading.value = false;
    });
};
let startX = 0;
let startWidth = 0;

const startResize = (event) => {
  startX = event.clientX;
  startWidth = leftWidth.value;
  window.addEventListener('mousemove', onResize);
  window.addEventListener('mouseup', stopResize);
};

const onResize = (event) => {
  const dx = event.clientX - startX;
  const newWidth = startWidth + (dx / window.innerWidth) * 100;
  leftWidth.value = Math.max(10, Math.min(90, newWidth)); // 限制宽度在10%到90%之间
};

const stopResize = () => {
  window.removeEventListener('mousemove', onResize);
  window.removeEventListener('mouseup', stopResize);
};

const getList = () => {
  loading.value = true;
  if (isDelete.value) {
    queryParams.value.nodeId = '1879453303423115265';
    queryParams.value.modelId = '';
  }
  return getElementModel(queryParams.value)
    .then((res) => {
      metaList.value = res.rows || [];
      total.value = res.total || 0;
    })
    .catch(() => {
      metaList.value = [];
      total.value = 0;
    })
    .finally(() => {
      loading.value = false;
    });
};
const setNodeAfterWidth = () => {
  if (!deptTreeRef.value) return;
  nextTick(() => {
    document.querySelectorAll('.el-tree-node').forEach((node) => {
      if (node.querySelector('.el-tree-node__expand-icon.expanded')) {
        node.style.setProperty('--after-width', '18px');
      } else {
        node.style.setProperty('--after-width', '30px');
      }
    });
  });
};

watch(
  () => treeData.value,
  () => {
    setNodeAfterWidth();
  },
  { deep: true }
);

onMounted(() => {
  getBusinessSystemList({
    type: 0,
    pageNum: 1,
    pageSize: 9999
  }).then((res) => {
    if (res) {
      businessScenariosList.value = res.rows || [];
    }
  });

  getTreeList({ name: '' }).then((res) => {
    if (res) {
      databaseList.value = res || [];
      databaseListCopy.value = JSON.parse(JSON.stringify(databaseList.value));
    }
  });
  getList().then(() => {
    getTreeData();
  });
  window.addEventListener('click', handleClick);
  setNodeAfterWidth();
});
onUnmounted(() => {
  window.removeEventListener('click', handleClick);
  window.removeEventListener('mousemove', onResize);
  window.removeEventListener('mouseup', stopResize);
});
</script>

<style lang="scss" scoped>
.structure_left {
  padding-right: 5px;
}
.card {
  height: calc(100vh - 100px);
  overflow: auto;
  padding: 5px 0 50px 0;
}
.explanation {
  font-size: 13px;
  font-weight: bold;
  height: 20px;
  line-height: 20px;
  color: #606266;
}

.sub_explanation {
  font-size: 12px;
  height: 20px;
  display: flex;
  align-items: center;
  color: #707477;
  margin-right: 15px;
}
.resizer {
  position: relative;
  width: 0.3%;
  background-color: #d9d9d9;
  cursor: ew-resize;
  border-radius: 5px;
}

.model_display {
  padding-left: 5px;
}

/* 树形结构节点添加连线 */
:deep .tree {
  .el-tree-node {
    position: relative;
    padding-left: 10px;
    /* 缩进量 */
  }

  .el-tree-node__children {
    padding-left: 15px;
    /* 缩进量 */
  }

  /* 竖线 */
  .el-tree-node::before {
    content: '';
    height: 100%;
    width: 1px;
    position: absolute;
    left: -3px;
    top: -26px;
    border-width: 1px;
    border-left: 1px dashed #52627c;
  }

  /* 当前层最后一个节点的竖线高度固定 */
  .el-tree-node:last-child::before {
    height: 40px;
    /* 可以自己调节到合适数值 */
  }

  /* 横线 */
  .el-tree-node::after {
    content: '';
    width: var(--after-width, 30px);
    height: 20px;
    position: absolute;
    left: -3px;
    top: 13px;
    border-width: 1px;
    border-top: 1px dashed #52627c;
  }

  /* 去掉最顶层的虚线，放最下面样式才不会被上面的覆盖了 */
  & > .el-tree-node::after {
    border-top: none;
  }

  & > .el-tree-node::before {
    border-left: none;
  }

  /* 展开关闭的icon */
  .el-tree-node__expand-icon {
    font-size: 12px;
    /* 叶子节点（无子节点） */
    &.is-leaf {
      color: transparent;
      /* 也可以去掉 */
      // display: none;
      width: 12px;
    }
  }
}
.sub_title {
  font-size: 14px;
  color: #606266;
  margin-left: 5px;
}
.custom-menu {
  position: absolute;
  background-color: #fff;
  border: 1px solid #ebebeb;
  border-radius: 3px;
  width: 110px;
  z-index: 1000;
  font-size: 12px;
  ul {
    margin: 0;
    padding: 5px 0;
    list-style: none;
    font-size: 12px;
  }
  ul li {
    padding: 3px 15px;
    cursor: pointer;
    font-size: 12px;
    display: flex;
    align-items: center;
  }
  ul li:hover {
    background-color: #eee;
  }
}
:deep(.el-tree-node__label) {
  font-size: 12px;
}
</style>
